<!--
  - Licensed to the Apache Software Foundation (ASF) under one or more
  - contributor license agreements.  See the NOTICE file distributed with
  - this work for additional information regarding copyright ownership.
  - The ASF licenses this file to You under the Apache License, Version 2.0
  - (the "License"); you may not use this file except in compliance with
  - the License.  You may obtain a copy of the License at
  -
  -     http://www.apache.org/licenses/LICENSE-2.0
  -
  - Unless required by applicable law or agreed to in writing, software
  - distributed under the License is distributed on an "AS IS" BASIS,
  - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  - See the License for the specific language governing permissions and
  - limitations under the License.
  -->

<template>
  <el-row class="box-card">
    <div class="btn-group">
      <el-button
        :disabled="isGuest"
        class="btn-plus"
        type="primary"
        icon="el-icon-plus"
        @click="add"
      >{{ $t("registryCenter.btnTxt") }}</el-button>
    </div>
    <div class="btn-group pull-right" style="float: right;">
      <el-input
        v-model="searchForm.account"
        placeholder="Search"
        clearable
        autocomplete="off"
        @clear="search"
        @change="search" >
        <i slot="prefix" class="el-input__icon el-icon-search"></i>
        <el-button
          slot="append"
          icon="el-icon-search"
          @click="search"></el-button>
      </el-input>
    </div>
    <div class="table-wrap">
      <el-table
        :data="tableData"
        stripe
        border
        style="width: 100%">
        <el-table-column
          v-for="(item, index) in column"
          :key="index"
          :prop="item.prop"
          :label="item.label"
          :width="item.width"
        >
          <template slot-scope="scope">
            <span v-if="'password'===item.prop"> ********* </span>
            <span v-else-if="'status'!==item.prop">{{ scope.row[item.prop] }}</span>
            <el-button
              v-if="'status'===item.prop"
              :type="statusColor[scope.row[item.prop]]"
              size="mini"
              plain>
              {{ $t("userManage.statusText."+scope.row[item.prop]) }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('userManage.registDialog.operate')"
          fixed="right"
          width="400">
          <template slot-scope="scope">
            <el-button-group>
              <el-button
                size="mini"
                type="primary"
                plain
                @click="handleEdit(scope.row)">{{ $t("userManage.actionText.edit") }}</el-button>
              <el-button
                :disabled="isGuest"
                size="mini"
                type="success"
                plain
                @click="handleEnable(scope.row)">{{ $t("userManage.actionText.enable") }}</el-button>
              <el-button
                :disabled="isGuest"
                size="mini"
                type="warning"
                plain
                @click="handleDisable(scope.row)">{{ $t("userManage.actionText.disable") }}</el-button>
              <el-button
                :disabled="isGuest"
                size="mini"
                type="info"
                plain
                @click="handleDevolve(scope.row)">{{ $t("userManage.actionText.devolve") }}</el-button>
              <el-button
                :disabled="isGuest"
                size="mini"
                type="danger"
                icon="el-icon-delete"
                plain
                @click="handlerRemove(scope.row)">{{ $t("operationServers.actionText.remove") }}</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          :total="total"
          :current-page="currentPage"
          background
          layout="prev, pager, next"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <el-dialog
      :title="$t('userManage.registDialog.title')"
      :visible.sync="addDialogVisible"
      width="610px"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item :label="$t('userManage.registDialog.account')" prop="account">
          <el-input :placeholder="$t('userManage.rules.account')" v-model="form.account" autocomplete="off" />
        </el-form-item>
        <el-form-item :label="$t('userManage.registDialog.userName')" prop="userName">
          <el-input
            :placeholder="$t('userManage.rules.userName')"
            v-model="form.userName"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item :label="$t('userManage.registDialog.password')" prop="password">
          <el-input
            :placeholder="$t('userManage.rules.password')"
            v-model="form.password"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item :label="$t('userManage.registDialog.status')">
          <el-select v-model="form.status" :placeholder="$t('userManage.rules.status')">
            <el-option
              v-for="item in $t('userManage.selectText')"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">{{ $t("userManage.registDialog.btnCancelTxt") }}</el-button>
        <el-button
          type="primary"
          @click="onConfirm('form')"
        >{{ $t("userManage.registDialog.btnConfirmTxt") }}</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="$t('userManage.registDialog.devolve')"
      :visible.sync="devolveDialogVisible"
      width="610px"
    >
      <el-form ref="devolveForm" :model="devolveForm" :rules="devolveRules" label-width="100px">
        <el-form-item :label="$t('userManage.registDialog.account')" prop="toAccount">
          <el-input :placeholder="$t('userManage.rules.account')" v-model="devolveForm.toAccount" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="devolveDialogVisible = false">{{ $t("userManage.registDialog.btnCancelTxt") }}</el-button>
        <el-button
          type="primary"
          @click="onConfirm2('devolveForm')"
        >{{ $t("userManage.registDialog.btnConfirmTxt") }}</el-button>
      </div>
    </el-dialog>

  </el-row>
</template>
<script>
import { mapActions } from 'vuex'
import clone from 'lodash/clone'
import API from '../api'
export default {
  name: 'UserManage',
  data() {
    return {
      addDialogVisible: false,
      devolveDialogVisible: false,
      isGuest: window.localStorage.getItem('isGuest') === 'true',
      column: [
        {
          label: this.$t('userManage').registDialog.account,
          prop: 'account'
        },
        {
          label: this.$t('userManage').registDialog.userName,
          prop: 'userName'
        },
        {
          label: this.$t('userManage').registDialog.password,
          prop: 'password'
        },
        {
          label: this.$t('userManage').registDialog.status,
          prop: 'status'
        }
      ],
      searchForm: {
        account: ''
      },
      form: {
        account: '',
        userName: '',
        password: '',
        status: ''
      },
      devolveForm: {
        fromAccount: '',
        toAccount: ''
      },
      rules: {
        account: [
          {
            required: true,
            message: this.$t('userManage').rules.account,
            trigger: 'change'
          }
        ],
        password: [
          {
            required: true,
            message: this.$t('userManage').rules.password,
            trigger: 'change'
          }
        ],
        userName: [
          {
            required: true,
            message: this.$t('userManage').rules.userName,
            trigger: 'change'
          }
        ],
        status: [
          {
            required: true,
            message: this.$t('userManage').rules.status,
            trigger: 'change'
          }
        ]
      },
      devolveRules: {
        toAccount: [
          {
            required: true,
            message: this.$t('userManage').rules.account,
            trigger: 'change'
          }
        ]
      },
      statusColor: {
        OK: 'success',
        DISABLED: 'warning'
      },
      tableData: [],
      cloneTableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0
    }
  },
  created() {
    this.search()
  },
  methods: {
    ...mapActions(['setRegCenterActivated']),
    handleCurrentChange(val) {
      const data = clone(this.cloneTableData)
      this.currentPage = val
      this.tableData = data.splice(this.pageSize * (val - 1), this.pageSize)
    },
    getAllUserList() {
      var params = {
        account: this.searchForm.account
      }
      API.getUserList(params).then(res => {
        const data = Array.prototype.filter.call(res.model, this.filterSearchData)
        this.total = data.length
        this.cloneTableData = clone(data)
        this.tableData = data.splice(this.pageSize * (this.currentPage - 1), this.pageSize)
      })
    },
    filterSearchData(model) {
      if (!this.searchForm.account) {
        return true
      }
      if (!model) {
        return true
      }
      return model.account && model.account.toLowerCase().includes(this.searchForm.account.toLowerCase())
    },
    handleEdit(row) {
      this.addDialogVisible = true
      this.form = row
    },
    handleEnable(row) {
      const params = {
        account: row.account
      }
      API.enableUser(params).then(res => {
        this.$notify({
          title: this.$t('common').notify.title,
          message: this.$t('common').notify.actionSucMessage,
          type: 'success'
        })
        this.search()
      })
    },
    handleDisable(row) {
      const params = {
        account: row.account
      }
      API.disableUser(params).then(res => {
        this.$notify({
          title: this.$t('common').notify.title,
          message: this.$t('common').notify.actionSucMessage,
          type: 'success'
        })
        this.search()
      })
    },
    handleDevolve(row) {
      this.devolveForm.fromAccount = row.account
      this.devolveDialogVisible = true
    },
    handlerRemove(row) {
      const params = {
        account: row.account
      }
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        API.deleteUser(params).then(res => {
          this.$notify({
            title: this.$t('common').notify.title,
            message: this.$t('common').notify.delSucMessage,
            type: 'success'
          })
          this.search()
        })
      }).catch(() => {
      })
    },
    onConfirm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          API.saveUser(this.form).then(res => {
            this.addDialogVisible = false
            this.$notify({
              title: this.$t('common').notify.title,
              message: this.$t('common').notify.addSucMessage,
              type: 'success'
            })
            this.search()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    onConfirm2(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          API.devolveUser(this.devolveForm).then(res => {
            this.devolveDialogVisible = false
            this.$notify({
              title: this.$t('common').notify.title,
              message: this.$t('common').notify.actionSucMessage,
              type: 'success'
            })
            this.search()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    add() {
      this.addDialogVisible = true
      this.form = {
        account: '',
        userName: '',
        password: '',
        status: ''
      }
    },
    search() {
      this.getAllUserList()
    }
  }
}
</script>
<style lang='scss' scoped>
  .btn-group {
    margin-bottom: 20px;
  }
  .pagination {
    float: right;
    margin: 10px -10px 10px 0;
  }
  .el-form .el-col{
    padding-left: 4px;
  }
</style>
